package main

import (
	"encoding/json"
	"io/ioutil"
	"os"

	yaml "gopkg.in/yaml.v2"
)

var serverConf ServerConfType
var dbConf MySQLConfType

type MySQLConfType struct {
	DB_ALL []DBConfType `yaml:"DB_ALL"`
}

type DBConfType struct {
	Host   string      `yaml:"host"`
	Port   string      `yaml:"port"`
	User   string      `yaml:"user"`
	Pwd    string      `yaml:"pwd"`
	DBName string      `yaml:"db"`
	Msg    interface{} `yaml:"msg"`
}

// JSONConn SSH主机连接设置
type ServerConfType struct {
	ServerConf []IpConfType `json:"server_conf"`
}

type IpConfType struct {
	IP      string `json:"ip"`
	User    string `json:"user"`
	Pwd     string `json:"password"`
	PwdExe  string `json:"pwd_exe"`
	PwdParm string `json:"pwd_parm"`
}

func ReadMySQLConf(filepath string) {
	yamlFile, e := ioutil.ReadFile(filepath)
	if e != nil {
		ErrHandler(e, Fault)
	}
	e = yaml.Unmarshal(yamlFile, &dbConf)
	if e != nil {
		ErrHandler(e, Fault)
	}
	PrettyPrint(dbConf)
}

// ReadServerConf 读取服务器配置文件
func ReadServerConf(filepath string) {
	file, e := os.Open(filepath)
	defer file.Close()
	if e != nil {
		ErrHandler(e, Fault)
	}
	//fmt.Printf("%v\n", file)

	jsonParser := json.NewDecoder(file)

	e = jsonParser.Decode(&serverConf)
	if e != nil {
		ErrHandler(e, Fault)
	}
	//	fmt.Printf("Result: %+v\n", jConn)
	//	PrettyPrint(jConn)
}

// PrettyPrint 格式化结构体输出
// Study from https://siongui.github.io/2016/01/30/go-pretty-print-variable/
func PrettyPrint(v interface{}) {
	b, _ := json.MarshalIndent(v, "", "  ")
	println(string(b))
}
